<template>
  <el-dialog
  title="选择商品"
  :visible="visible"
  width="80%"
  custom-class="product-selector-dialog"

  @close="$emit('update:visible', false)"
  >
    <el-card class="search-box">
      <el-input
        v-model="searchKey"
        placeholder="输入商品名称搜索"
        style="width: 300px"
        clearable
        @input="handleSearch"
      />
      <el-button type="primary" @click="handleSearch" style="margin-left: 15px">
        搜索
      </el-button>
    </el-card>

    <div class="product-grid" v-loading="loading"
    element-loading-text="商品加载中...">
      <div
        v-for="product in tableData"
        :key="product.id"
        class="product-card"
        :class="{ selected: selectedProducts.some(p => p.id === product.id) }"
        @click="toggleSelection(product)"
      >
        <div class="image-container">
          <img :src="product.img || '/default-product.png'" alt="商品图片" />
          <div class="selection-mask">
            <el-icon class="check-icon"><Select /></el-icon>
          </div>
        </div>
        <div class="product-info">
          <h4 class="name">{{ product.name }}</h4>
          <p class="price">¥ {{ product.price.toFixed(2) }}</p>
        </div>
      </div>
    </div>

    <el-pagination
      background
      layout="total, sizes, prev, pager, next"
      :total="total"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      @current-change="fetchData"
      @size-change="handleSizeChange"
      style="margin-top: 20px"
    />

    <template #footer>
      <el-button @click="$emit('update:visible', false)">取消</el-button>
      <el-button type="primary" @click="confirmSelection">确认选择</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watchEffect } from 'vue';
import { ElMessage } from 'element-plus';
import { get_products } from '@/api/products/index';

const props = defineProps({
  visible: Boolean
});

const emit = defineEmits(['update:visible', 'select']);

const searchKey = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref<any[]>([]);
const loading = ref(false);
const selectedProducts = ref<any[]>([]);

const fetchData = async () => {
  try {
    loading.value = true;
    const res = await get_products({
      key: searchKey.value,
      page: currentPage.value,
      limit: pageSize.value
    });

    if (res.code === 0) {
      tableData.value = res.data.data;
      total.value = res.data.total;
    }
  } catch (error) {
    ElMessage.error('获取商品失败');
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchData();
};

const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

const handleSelectionChange = (selection: any[]) => {
  selectedProducts.value = selection;
};

const toggleSelection = (product: any) => {
  const index = selectedProducts.value.findIndex(p => p.id === product.id)
  if (index > -1) {
    selectedProducts.value.splice(index, 1)  // 取消选择
  } else {
    selectedProducts.value.push(product)    // 添加选择
  }
}

// 修改确认选择逻辑
const confirmSelection = () => {
  emit('select', selectedProducts.value.map(p => ({
    id: p.id,
    name: p.name,
    price: p.price,
    img: p.img
  })))
  selectedProducts.value = [] // 新增这行清空选中状态
  emit('update:visible', false)
}

watchEffect(() => {
  if (props.visible) {
    fetchData();
  }
});

// 在选择商品时传递完整信息
const handleSelection = (selection) => {
  emit('select', selection.map(p => ({
    id: p.id,
    name: p.name,  // 确保包含名称
    price: p.price // 包含价格信息
  })))
}
</script>

<style scoped>
.search-box {
  margin-bottom: 20px;
  background: #f5f7fa;
}
.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  padding: 15px;
}

.product-card {
  border-radius: 8px;
  overflow: hidden;
  background: white;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: all 0.3s ease;
  cursor: pointer;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
  }

  &.selected {
    border: 2px solid #409EFF;
    .selection-mask {
      opacity: 1;
    }
  }
}

.image-container {
  position: relative;
  height: 160px;

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.selection-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(64, 158, 255, 0.3);
  opacity: 0;
  transition: opacity 0.3s;

  .check-icon {
    position: absolute;
    right: 8px;
    top: 8px;
    color: white;
    font-size: 24px;
  }
}

.product-info {
  padding: 12px;
  .name {
    margin: 0;
    font-size: 14px;
    color: #333;
    @include text-ellipsis;
  }
  .price {
    margin: 8px 0 0;
    color: #f56c6c;
    font-weight: bold;
  }
}
</style>
